//
//  LoginViewController.m
//  u76ho
//
//  Created by m-air-01 on 16/1/5.
//  Copyright © 2016年 LV. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "ForgetPasswordViewController.h"

#import <CoreLocation/CoreLocation.h>


//#import <AMapLocationKit/AMapLocationKit.h>
//
//#define AMPKey  @"5afdf7bc67e5d636b95c710fa6b85430"
//

@interface LoginViewController ()<UITextFieldDelegate,CLLocationManagerDelegate>
{
    NSMutableArray * nArr;
    
    NSMutableString * phoneNumStr;
    NSMutableString * passWordStr;
    
    BOOL isLoginout;
    
    NSString * lat;//经度
    NSString * lng;//纬度
}

@property (nonatomic,strong) CLLocationManager *locationManager;


@end

@implementation LoginViewController
#pragma mark - 视图生命周期
-(void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:YES];


    if (isLoginout == YES) {
        
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    lat = @"";
    lng = @"";
    ///获取系统点位
    [self xitongDingWei];
    
    [self main];
    // Do any additional setup after loading the view.
}
-(void)main
{
    phoneNumStr = [[NSMutableString alloc]init];
    passWordStr = [[NSMutableString alloc]init];
    
    nArr = [[NSMutableArray alloc]init];
    for (int i = 0; i<10; i++) {
        [nArr addObject:[NSString stringWithFormat:@"%i",i]];
    }

    
    self.view.backgroundColor = [UIColor whiteColor];
    UIImageView * bgImgV = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    bgImgV.image = [UIImage imageNamed:@"登录"];
    [self.view addSubview:bgImgV];
    
    UIButton * closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    closeBtn.frame = CGRectMake(SCREEN_WIDTH-34-SIZETO6W(25), 20, 34, 34);
    [closeBtn setImage:[UIImage imageNamed:@"关闭按钮"] forState:UIControlStateNormal];
    [closeBtn addTarget:self action:@selector(closeAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:closeBtn];
    
    UIImageView * yiqiZPImgV = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2-SIZETO6W(134)/2, SIZETO6H(125), SIZETO6W(134), SIZETO6H(32))];
    yiqiZPImgV.image = [UIImage imageNamed:@"益企招聘"];
    [self.view addSubview:yiqiZPImgV];
    
    //手机
    UIView * shoujiV = [[UIView alloc]initWithFrame:CGRectMake(SIZETO6W(29), yiqiZPImgV.bottom+SIZETO6H(56), SCREEN_WIDTH-SIZETO6W(29)*2, 47)];
    shoujiV.layer.masksToBounds = YES;
    shoujiV.layer.cornerRadius = 20;
    shoujiV.layer.borderWidth = 1;
    shoujiV.layer.borderColor = [[UIColor whiteColor] CGColor];
    shoujiV.backgroundColor = [UIColor clearColor];
    [self.view addSubview:shoujiV];
    
    UIImageView * shoujiImg = [[UIImageView alloc]initWithFrame:CGRectMake(SIZETO6W(20), shoujiV.height/2-22/2, 14, 22)];
    shoujiImg.image = [UIImage imageNamed:@"手机icon"];
    [shoujiV addSubview:shoujiImg];
    
    UITextField * shoujiTextField = [[UITextField alloc]initWithFrame:CGRectMake(shoujiImg.right+SIZETO6W(15), 0, shoujiV.width-shoujiImg.right-SIZETO6W(15), shoujiV.height)];
    UIColor * color = UIColorFromRGB(0xffffff);
    shoujiTextField.attributedPlaceholder = [[NSAttributedString alloc]initWithString:@"手机" attributes:@{NSForegroundColorAttributeName:color}];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 30, 30);
    [btn setImage:[UIImage imageNamed:@"关闭按钮-"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(clearBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    shoujiTextField.rightView = btn;
    shoujiTextField.tag = 100;
    [shoujiTextField addTarget:self action:@selector(NumChange:) forControlEvents:UIControlEventEditingChanged];

    shoujiTextField.rightViewMode = UITextFieldViewModeWhileEditing;
    shoujiTextField.keyboardType = UIKeyboardTypeNumberPad;

    shoujiTextField.textColor = color;
    shoujiTextField.placeholder = @"手机";
    [shoujiV addSubview:shoujiTextField];
    
    //密码
    UIView * mimaV = [[UIView alloc]initWithFrame:CGRectMake(SIZETO6W(29), shoujiV.bottom+SIZETO6H(15), SCREEN_WIDTH-SIZETO6W(29)*2, 47)];
    mimaV.layer.masksToBounds = YES;
    mimaV.layer.cornerRadius = 20;
    mimaV.layer.borderWidth = 1;
    mimaV.layer.borderColor = [[UIColor whiteColor] CGColor];
    mimaV.backgroundColor = [UIColor clearColor];
    [self.view addSubview:mimaV];
    
    UIImageView *mimaImg = [[UIImageView alloc]initWithFrame:CGRectMake(SIZETO6W(20), mimaV.height/2-18/2, 15, 18)];
    mimaImg.image = [UIImage imageNamed:@"密码icon"];
    [mimaV addSubview:mimaImg];
    
    UITextField * mimaTextField = [[UITextField alloc]initWithFrame:CGRectMake(mimaImg.right+SIZETO6W(15), 0, mimaV.width-mimaImg.right-SIZETO6W(15), mimaV.height)];
    mimaTextField.attributedPlaceholder = [[NSAttributedString alloc]initWithString:@"密码" attributes:@{NSForegroundColorAttributeName:color}];
    mimaTextField.textColor = color;
    mimaTextField.delegate = self;
    mimaTextField.secureTextEntry = YES;
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn2.frame = CGRectMake(0, 0, 30, 30);
    [btn2 setImage:[UIImage imageNamed:@"关闭按钮-"] forState:UIControlStateNormal];
    [btn2 addTarget:self action:@selector(clearBtnClick2:) forControlEvents:UIControlEventTouchUpInside];
    [mimaTextField addTarget:self action:@selector(passwordChange:) forControlEvents:UIControlEventEditingChanged];
    mimaTextField.keyboardType = UIKeyboardTypeASCIICapable;

    mimaTextField.tag = 101;
    mimaTextField.rightViewMode = UITextFieldViewModeWhileEditing;
    mimaTextField.rightView = btn2;
    
    [mimaV addSubview:mimaTextField];

    //忘记密码
    UIButton * forgetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    forgetBtn.frame = CGRectMake(mimaV.right-100, mimaV.bottom + SIZETO6H(14), 90, 30);
    [forgetBtn setTitle:@"忘记密码?" forState:UIControlStateNormal];
    [forgetBtn addTarget:self action:@selector(forgetBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [forgetBtn setTitleColor:UIColorFromRGB(0xFFFFFF) forState:UIControlStateNormal];
    [self.view addSubview:forgetBtn];
    
    //登录
    UIButton * loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    loginBtn.frame = CGRectMake(SIZETO6W(29), forgetBtn.bottom+SIZETO6PlusH(25), SCREEN_WIDTH-SIZETO6W(29)*2, 47);
    [loginBtn setBackgroundColor:UIColorFromRGB(0x6ec844)];
    loginBtn.layer.masksToBounds = YES;
    loginBtn.layer.cornerRadius = 20;
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(loginBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [loginBtn setTitleColor:UIColorFromRGB(0xFFFFFF) forState:UIControlStateNormal];
    [self.view addSubview:loginBtn];
    //注册
    UIButton * registerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    registerBtn.frame = CGRectMake(SCREEN_WIDTH/2-SIZETO6W(120)/2, SCREEN_HEIGHT -100, SIZETO6W(120), 40);
    registerBtn.layer.masksToBounds = YES;
    registerBtn.layer.borderColor = [UIColorFromRGB(0xffffff) CGColor];
    registerBtn.layer.borderWidth = 1.0f;
    registerBtn.layer.cornerRadius = 20;
    [registerBtn setTitleColor:UIColorFromRGB(0xffffff) forState:UIControlStateNormal];
    [registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    [registerBtn addTarget:self action:@selector(registerAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:registerBtn];
}
-(void)loginwithclient:(NSString *)client username:(NSString *)username userpwd:(NSString *)userpwd withLat:(NSString *)lat withLng:(NSString *)lng
{
    __weak typeof(self)weakSelf = self;
    
  [U76HONet loginWithaction:@"" Client:client Username:username Userpwd:userpwd withLat:lat withLong:lng andDataBlock:^(LoginModel *model) {
      NSLog(@"登录成功了");
      //保存登录的code
      [Singleton share].code = model.code;
      [Singleton share].yqcode = model.qycode;
      [Singleton share].mobile = model.mobile;
      [Singleton share].password = userpwd;
      
      [Singleton share].duty = model.duty;
      
      [[Singleton share] saveUserInformation];
      [[NSNotificationCenter defaultCenter] postNotificationName:@"loginSuccess" object:nil];
      if (_isPopVC) {
          [weakSelf dismissViewControllerAnimated:YES completion:nil];
          return;
      }
      
      if (_isHome) {
         
          [weakSelf dismissViewControllerAnimated:YES completion:nil];
          
         
          return;
      }
      
      [weakSelf dismissViewControllerAnimated:YES completion:nil];
     
      
  }];

}

// 错误信息
-(void)LocationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    //    [MMProgressHUD dismissWithError:@"locating Error"];
    NSLog(@"error");
}

-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            if([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
                [_locationManager requestWhenInUseAuthorization];
            break;
            
        default:
            break;
    }
}

// 6.0 以上调用这个函数

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *newLocation = locations[0];
    CLLocationCoordinate2D newCoordinate = newLocation.coordinate;
    NSLog(@"经度：%f,纬度：%f",newCoordinate.longitude,newCoordinate.latitude);
    
    lat = [NSString stringWithFormat:@"%f",newCoordinate.latitude];
    
    lng = [NSString stringWithFormat:@"%f",newCoordinate.longitude];
    
    
    // 计算两个坐标距离
    //    float distance = [newLocation distanceFromLocation:oldLocation];
    [manager stopUpdatingLocation];
    manager.delegate =nil;
}






-(void)NumChange:(UITextField *)textField
{
    UITextField * passWordTF = (UITextField *)[self.view viewWithTag:101];
    if (textField.text.length > phoneNumStr.length) {
        if (textField.text.length <= 11 ) {
            
            NSString * s = [textField.text substringWithRange:NSMakeRange(textField.text.length-1, 1)];
            if ([nArr containsObject:s] ) {
                [phoneNumStr appendString:s];
            }
        }
    }
    else if([textField.text isEqualToString:@""])
    {
        phoneNumStr = [[NSMutableString alloc]init];
        passWordStr = [[NSMutableString alloc]init];
        passWordTF.text = @"";
    }
    else
    {
        NSString * str = [phoneNumStr substringToIndex:(phoneNumStr.length-1)];
        phoneNumStr = [[NSMutableString alloc]initWithString:str];
    }
    
    textField.text = phoneNumStr;
    
    
}
-(void)passwordChange:(UITextField *)textField
{
    if (textField.text.length > passWordStr.length) {
        if (textField.text.length <= 16) {
            
            NSString * s = [textField.text substringWithRange:NSMakeRange(textField.text.length-1, 1)];
            
            [passWordStr appendString:s];
            
        }
    }
    else if([textField.text isEqualToString:@""])
    {
        passWordStr = [[NSMutableString alloc]init];
    }
    else
    {
        NSString * str = [passWordStr substringToIndex:passWordStr.length-1];
        passWordStr = [[NSMutableString alloc]initWithString:str];
    }
    textField.text = passWordStr;

}
-(void)clearBtnClick:(id)sender
{
    UITextField * textField = (UITextField *)[self.view viewWithTag:100];
    textField.text = @"";
    UITextField * textField2 = (UITextField *)[self.view viewWithTag:101];
    textField2.text = @"";
    
    phoneNumStr = [[NSMutableString alloc]init];
    passWordStr = [[NSMutableString alloc]init];
    
}
-(void)clearBtnClick2:(id)sender
{
    UITextField * textField = (UITextField *)[self.view viewWithTag:101];
    textField.text = @"";
    passWordStr = [[NSMutableString alloc]init];
    
}
//系统定位
-(void)xitongDingWei
{
    

        
        if([CLLocationManager locationServicesEnabled]){
            self.locationManager = [[CLLocationManager alloc]init];
            _locationManager.delegate = self;
            _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
            _locationManager.distanceFilter = 0;
            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
                [_locationManager requestWhenInUseAuthorization];//使用程序其间允许访问位置数据（iOS8定位需要）
            }
            BOOL enable=[CLLocationManager locationServicesEnabled];
            //是否具有定位权限
            int status=[CLLocationManager authorizationStatus];
            if(enable && (status>=3||status ==kCLAuthorizationStatusNotDetermined)){
                //        [MMProgressHUD showWithTitle:@"locating" status:@""];
                [_locationManager startUpdatingLocation];
            }
        }
            
            

    
}


#pragma mark - 登录
-(void)loginBtnAction:(UIButton *)btn
{
    //手机号码
    UITextField * phoneNumTextField = (UITextField *)[self.view viewWithTag:100];
    
    //密码
    UITextField * passwordTextField = (UITextField *)[self.view viewWithTag:101];
    
    if (![passwordTextField.text isEqualToString:@""] && ![phoneNumTextField.text isEqualToString:@""]) {
        
        if (lng&&lat) {
            
            [self loginwithclient:@"123654" username:phoneNumTextField.text userpwd:passwordTextField.text withLat:lat withLng:lng];
            
        }else{
        
        [self loginwithclient:@"123654" username:phoneNumTextField.text userpwd:passwordTextField.text withLat:@"" withLng:@""];
        
        }

        
        
        
        
    }
}
#pragma Mark  忘记密码
-(void)forgetBtnAction:(UIButton *)btn
{
    ForgetPasswordViewController * forgetPasswordVC = [[ForgetPasswordViewController alloc]init];
    //[self presentViewController:forgetPasswordVC animated:YES completion:nil];
    [self.navigationController pushViewController:forgetPasswordVC animated:YES];
}
#pragma mark --注册点击事件
-(void)registerAction:(UIButton *)btn
{
    RegisterViewController * registerVC = [[RegisterViewController alloc]init];
    
    
    [self.navigationController pushViewController:registerVC animated:YES];
}
-(void)closeAction:(id)sender
{
    
    
    
    if (_isPopVC) {
        [self dismissViewControllerAnimated:YES completion:nil];
        return;
    }
    
    if (_isHome) {
        [self dismissViewControllerAnimated:YES completion:nil];
        return;
    }
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
//    AppDelegate * app = [UIApplication sharedApplication].delegate;
//    self.view.window.rootViewController = app.viewController;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if ([string isEqualToString:@"\n"]) {
        NSLog(@"开始登录了");
        
        //手机号码
        UITextField * phoneNumTextField = (UITextField *)[self.view viewWithTag:100];
        
        //密码
        UITextField * passwordTextField = (UITextField *)[self.view viewWithTag:101];
        
        if (![passwordTextField.text isEqualToString:@""] && ![phoneNumTextField.text isEqualToString:@""]) {
            [self loginwithclient:@"123654" username:phoneNumTextField.text userpwd:passwordTextField.text withLat:lat withLng:lng];
            
            
           // [self loginwithclient:@"123654" username:phoneNumTextField.text userpwd:passwordTextField.text];
        }
        
        
        return NO;
    }
    return YES;
    
    
    
    
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
